package cn.edu.zafu.bigdata.x.zbw;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileOperations {

    // 写入文件的方法
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件的方法
    public static String readFromFile(String fileName) {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return contentBuilder.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文本：");
        String inputText = scanner.nextLine();
        String studentId = "202211080116"; // 假设学号为2022010101
        String fileName = "files/" + studentId + ".txt"; // 文件路径

        // 将用户输入的文本写入文件
        writeToFile(fileName, inputText);

        // 读取文件内容并打印到控制台
        String fileContent = readFromFile(fileName);
        System.out.println("文件内容为：");
        System.out.println(fileContent);

        scanner.close();
    }
}
